package controller;

import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.imageio.ImageIO;

import model.Food;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import dao.FoodDAO;

@Controller
public class FoodController {
	private static final int IMG_WIDTH = 100;
	private static final int IMG_HEIGHT = 100;
	String url = "";
	String rootPath = System.getProperty("user.dir");
	@Autowired
	private FoodDAO dao;

	@RequestMapping(value = "/foodlist", method = RequestMethod.GET)
	public ModelAndView foodList() {
		List<Food> list = dao.getList();
		Map<String, Object> model = new HashMap<String, Object>();
		url = "foodlist";
		model.put("list", list);
		model.put("url", url);
		return new ModelAndView("../../Homepage", model);
	}

	@RequestMapping(value = "/addfood", method = RequestMethod.POST)
	public ModelAndView addFood(@ModelAttribute Food food) {
		Map<String, Object> model = new HashMap<String, Object>();
		url = "foodinfo";
		if (food.getId()==0) {
			String name = food.getName();
			File dir = new File(rootPath + File.separator + "workspace"
					+ File.separator + "CNPM" + File.separator + "WebContent"
					+ File.separator + "resources" + File.separator + "image");
			Food.makeQR(name, dir.getAbsolutePath() + File.separator + "qr" + name
					+ ".jpg");
			String filePath = "/resources/image/qr" + name + ".jpg";
			food.setQr(filePath);
		}
		dao.saveOrUpdate(food);
		model.put("url", url);
		return new ModelAndView("../../Homepage", model);
	}

	@RequestMapping(value = "/displayaddfood", method = RequestMethod.GET)
	public ModelAndView displayAddFood() {
		Map<String, Object> model = new HashMap<String, Object>();
		url = "displayaddfood";
		model.put("url", url);
		model.put("food", new Food());
		return new ModelAndView("../../Homepage", model);
	}

	@RequestMapping(value = "/displayupload", method = RequestMethod.GET)
	public String displayUpload() {
		return "Upload";
	}

	@RequestMapping(value = "/upload", method = RequestMethod.POST)
	public ModelAndView upload(@RequestParam("file") MultipartFile file) {
		Map<String, Object> model = new HashMap<String, Object>();
		String message = "";
		if (!file.isEmpty()) {
			try {
				byte[] bytes = file.getBytes();

				File dir = new File(rootPath + File.separator + "workspace"
						+ File.separator + "CNPM" + File.separator
						+ "WebContent" + File.separator + "resources"
						+ File.separator + "image");
				if (!dir.exists())
					dir.mkdirs();

				Calendar cal = Calendar.getInstance();
				SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
				String name = sdf.format(cal.getTime());
				File serverFile = new File(dir.getAbsolutePath()
						+ File.separator + "img" + name + ".jpg");
				BufferedOutputStream stream = new BufferedOutputStream(
						new FileOutputStream(serverFile));
				stream.write(bytes);
				stream.close();
				resizeIMG(serverFile);
				String filePath = "/resources/image/img" + name + ".jpg";
				model.put("filepath", filePath);
				message = "You successfully uploaded file";
			} catch (Exception e) {
				message = "You failed to upload => " + e.getMessage();
			}
		} else {
			message = "You failed to upload because the file was empty.";
		}
		model.put("message", message);
		return new ModelAndView("Upload", model);
	}

	public static void resizeIMG(File file) {
		try {

			BufferedImage originalImage = ImageIO.read(file);
			int type = originalImage.getType() == 0 ? BufferedImage.TYPE_INT_ARGB
					: originalImage.getType();

			BufferedImage resizeImageJpg = resizeImage(originalImage, type);
			ImageIO.write(resizeImageJpg, "jpg",
					new File(file.getAbsolutePath()));

		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private static BufferedImage resizeImage(BufferedImage originalImage,
			int type) {
		BufferedImage resizedImage = new BufferedImage(IMG_WIDTH, IMG_HEIGHT,
				type);
		Graphics2D g = resizedImage.createGraphics();
		g.drawImage(originalImage, 0, 0, IMG_WIDTH, IMG_HEIGHT, null);
		g.dispose();

		return resizedImage;
	}
}
